package Java241201;
class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
        val = x;
        next = null;
        }
        }

class PartitionList {
    public ListNode partition(ListNode head, int x) {
        if (head == null) {
            return head;
        }

        ListNode smallDummy = new ListNode(0);
        ListNode bigDummy = new ListNode(0);
        ListNode smallTail = smallDummy;
        ListNode bigTail = bigDummy;

        while (head != null) {
            if (head.val < x) {
                smallTail.next = head;
                smallTail = smallTail.next;
            } else {
                bigTail.next = head;
                bigTail = bigTail.next;
            }
            head = head.next;
        }

        smallTail.next = bigDummy.next;
        bigTail.next = null; // terminate the "big" list

        return smallDummy.next;
    }

    public static void main(String[] args) {
        // Example usage
        ListNode head = new ListNode(3);
        head.next = new ListNode(2);
        head.next.next = new ListNode(5);
        head.next.next.next = new ListNode(8);
        head.next.next.next.next = new ListNode(1);
        head.next.next.next.next.next = new ListNode(4);

        PartitionList partitioner = new PartitionList();
        ListNode partitionedHead = partitioner.partition(head, 4);

        // Print the partitioned list
        while (partitionedHead != null) {
            System.out.print(partitionedHead.val + " ");
            partitionedHead = partitionedHead.next;
        }
    }
}